from flask import Flask, jsonify, request
from flask_cors import CORS
import json
import os
from datetime import datetime

app = Flask(__name__)
CORS(app)

# 数据文件路径
DATA_FILE = 'data/tools.json'

def load_tools():
    """加载工具配置"""
    if os.path.exists(DATA_FILE):
        with open(DATA_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    return []

def save_tools(tools):
    """保存工具配置"""
    os.makedirs(os.path.dirname(DATA_FILE), exist_ok=True)
    with open(DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump(tools, f, ensure_ascii=False, indent=2)

@app.route('/api/tools', methods=['GET'])
def get_tools():
    """获取所有工具"""
    tools = load_tools()
    return jsonify(tools)

@app.route('/api/tools', methods=['POST'])
def create_tool():
    """创建新工具"""
    tool = request.json
    tool['id'] = f"tool_{int(datetime.now().timestamp())}_{os.urandom(4).hex()}"
    tool['createdAt'] = datetime.now().isoformat()
    
    tools = load_tools()
    tools.append(tool)
    save_tools(tools)
    
    return jsonify(tool), 201

@app.route('/api/tools/<tool_id>', methods=['PUT'])
def update_tool(tool_id):
    """更新工具"""
    updates = request.json
    tools = load_tools()
    
    for i, tool in enumerate(tools):
        if tool['id'] == tool_id:
            tools[i].update(updates)
            save_tools(tools)
            return jsonify(tools[i])
    
    return jsonify({'error': 'Tool not found'}), 404

@app.route('/api/tools/<tool_id>', methods=['DELETE'])
def delete_tool(tool_id):
    """删除工具"""
    tools = load_tools()
    tools = [t for t in tools if t['id'] != tool_id]
    save_tools(tools)
    return '', 204

@app.route('/api/health', methods=['GET'])
def health():
    """健康检查"""
    return jsonify({
        'status': 'ok',
        'message': 'DTSEToolBox API is running',
        'timestamp': datetime.now().isoformat()
    })

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)


